<template>
  <div class="purpose-scope-container">
    <div class="form-container">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="140px" class="purpose-form">
        <!-- 项目基本信息 -->
        <div class="form-section">
          <h2 class="section-title">项目基本信息</h2>
          <el-form-item label="项目编号" prop="projectId">
            <el-input v-model="formData.projectId" disabled />
          </el-form-item>
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="formData.projectName" />
          </el-form-item>
          <el-form-item label="项目目的" prop="purpose">
            <el-input v-model="formData.purpose" type="textarea" :rows="3" />
          </el-form-item>
        </div>

        <!-- 产品信息 -->
        <div class="form-section">
          <h2 class="section-title">产品信息</h2>
          <el-form-item label="产品编号" prop="productId">
            <el-input v-model="formData.productId" disabled />
          </el-form-item>
          <el-form-item label="产品名称" prop="productName">
            <el-input v-model="formData.productName" disabled />
          </el-form-item>
        </div>

        <!-- 评价范围 -->
        <div class="form-section">
          <h2 class="section-title">评价范围</h2>
          <el-form-item label="系统边界" prop="systemBoundary">
            <el-select v-model="formData.systemBoundary" placeholder="请选择系统边界">
              <el-option label="从摇篮到大门" value="从摇篮到大门" />
            </el-select>
          </el-form-item>
          <el-form-item prop="functionalUnit">
            <template #label>
              <div class="label-with-icon">
                <el-tooltip
                  effect="dark"
                  content="功能单位用于统一碳足迹计算基准，确保结果可比。请填写可量化的单位，如 '1kg 产品'、'1m² 涂层（1年）'、'1kWh 电力' 等。"
                  placement="top"
                >
                  <el-icon class="info-icon"><InfoFilled /></el-icon>
                </el-tooltip>
                <span>功能单位</span>
              </div>
            </template>
            <el-input v-model="formData.functionalUnit" placeholder="请输入功能单位" />
          </el-form-item>
          <el-form-item label="数据采集时间" prop="dataCollectionTime">
            <el-date-picker
              v-model="formData.dataCollectionTime"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </div>

        <!-- 评价方法 -->
        <div class="form-section">
          <h2 class="section-title">评价方法</h2>
          <el-form-item label="核算依据" prop="accountingBasis">
            <el-select v-model="formData.accountingBasis" placeholder="请选择核算依据">
              <el-option label="ISO 14067 : 2018" value="ISO 14067 : 2018" />
            </el-select>
          </el-form-item>
          <el-form-item label="核算方法" prop="accountingMethod">
            <el-select v-model="formData.accountingMethod" placeholder="请选择核算方法">
              <el-option label="碳排因子法" value="碳排因子法" />
            </el-select>
          </el-form-item>
        </div>

        <!-- 数据要求 -->
        <div class="form-section">
          <h2 class="section-title">
            <el-tooltip
              effect="dark"
              content="根据评价的目的和范围，应对评价的有关数据及其质量要求进行规定或说明。包括数据种类、数据来源、数据取舍原则、数据质量要求等。"
              placement="top"
            >
              <el-icon class="info-icon"><InfoFilled /></el-icon>
            </el-tooltip>
            数据要求
          </h2>
          <el-form-item label="数据取舍原则" prop="dataPrinciple">
            <el-input v-model="formData.dataPrinciple" type="textarea" :rows="3" placeholder="请输入数据取舍原则" disabled />
          </el-form-item>
          <el-form-item label="数据质量要求" prop="dataQuality">
            <el-input v-model="formData.dataQuality" type="textarea" :rows="3" placeholder="请输入数据质量要求" disabled />
          </el-form-item>
        </div>

        <!-- 按钮 -->
        <div class="form-actions">
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button type="primary" @click="handleNext">下一步</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watchEffect } from "vue";
import { ElMessage } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { InfoFilled } from "@element-plus/icons-vue";
import axios from "axios";
import { useTabsStore } from "@/stores/modules/tabs";
const tabStore = useTabsStore();
const formRef = ref();
const router = useRouter();
const route = useRoute();
const baseUrl = import.meta.env.VITE_BASE_URL;
// 表单数据
const formData = ref<any>({});

// 初始化表单数据
const initFormData = async () => {
  const projectId = route.params.projectId as string;

  //数据库
  const response = await axios.get(baseUrl + "/api/carbon/getPurposeScopeDataById?projectId=" + projectId);
  if (response) {
    formData.value = response.data.data;
    formData.value.dataCollectionTime = JSON.parse(response.data.data.dataCollectionTime);
    return;
  }
};

// 表单验证规则
const rules = {
  systemBoundary: [{ required: true, message: "请选择系统边界", trigger: "change" }],
  functionalUnit: [{ required: true, message: "请输入功能单位", trigger: "blur" }],
  dataCollectionTime: [{ required: true, message: "请选择数据采集时间", trigger: "change" }],
  accountingBasis: [{ required: true, message: "请选择核算依据", trigger: "change" }],
  accountingMethod: [{ required: true, message: "请选择核算方法", trigger: "change" }]
};

// 组件挂载时初始化数据
onMounted(() => {
  initFormData();
});

// 监听路由参数变化
watchEffect(() => {
  if (route.params.projectId) {
    initFormData();
  }
});

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    //保存到数据库
    formData.value.dataCollectionTime = JSON.stringify(formData.value.dataCollectionTime);
    const requestData = JSON.stringify(formData.value);
    console.log(requestData);
    formData.value.dataCollectionTime = JSON.parse(formData.value.dataCollectionTime);
    console.log(requestData);
    const response = await axios.post(baseUrl + "/api/carbon/savePurposeScopeDataById", requestData);
    console.log("更新结果：", response.data);

    // 保存到 localStorage
    // localStorage.setItem(`purposeScopeData_${formData.value.projectId}`, JSON.stringify(formData.value));
    ElMessage({
      type: "success",
      message: "保存成功"
    });
  } catch (error) {
    ElMessage({
      type: "error",
      message: "保存失败"
    });
  }
};

// 下一步
const handleNext = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    // 保存到 localStorage
    localStorage.setItem(`purposeScopeData_${formData.value.projectId}`, JSON.stringify(formData.value));
    if (route.meta.isAffix) return;
    tabStore.removeTabs(route.fullPath);
    // 跳转到清单分析界面
    router.push(`/lca/inventory/activityList/${formData.value.projectId}`);
  } catch (error) {
    ElMessage({
      type: "error",
      message: "请完善必填项"
    });
  }
};
</script>

<style scoped>
.purpose-scope-container {
  min-height: calc(100vh - 84px);
  padding: 20px;
  background-color: #f5f7fa;
}
.form-container {
  max-width: 1300px;
  padding: 30px;
  margin: 0 auto;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}
.form-section {
  padding-bottom: 20px;
  margin-bottom: 30px;
  border-bottom: 1px solid #ebeef5;
}
.section-title {
  padding-left: 10px;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 500;
  color: #303133;
  border-left: 4px solid #009688;
}
.form-actions {
  display: flex;
  gap: 20px;
  justify-content: center;
  margin-top: 40px;
}
:deep(.el-input.is-disabled .el-input__wrapper) {
  background-color: #f5f7fa;
}
:deep(.el-textarea.is-disabled .el-textarea__inner) {
  background-color: #f5f7fa;
}
:deep(.el-form-item) {
  margin-bottom: 22px;
}
:deep(.el-date-editor.el-input__wrapper) {
  width: 100%;
}
.label-with-icon {
  display: flex;
  gap: 4px;
  align-items: center;
}
.info-icon {
  font-size: 14px;
  color: #909399;
  cursor: help;
}
.info-icon:hover {
  color: #009688;
}
:deep(.el-form-item__label) {
  display: inline-flex;
  align-items: center;
}
</style>
